package org.robot;

import org.game.netty.oldcoder.other.CheckSumUtil;
import org.game.netty.oldcoder.other.ProtocolConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.manager.MessageManager;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * 消息对象工厂Netty实现，负责通过明文协议转换成消息对象的创建和解析校验工作
 * 
 * @author wk.dai
 */
public class EchoMessageFactory{
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final EchoMessageFactory DEFAULT_INSTANCE = new EchoMessageFactory();
	
	public static EchoMessageFactory getDefault() {
		return DEFAULT_INSTANCE;
	}

	public IMessage create(Object channel, Object data) {
		ChannelHandlerContext ctx = (ChannelHandlerContext) channel;
		ByteBuf in = (ByteBuf) data;
		short flag = in.readShort();
		int length = in.readInt();
		
		// 校验和
		short checksum = in.readShort();
		int checksumContentLength = length-ProtocolConstants.CHECKSUM_SKIP_SIZE_FOR_CONTENT;
		int bodyLength = length - ProtocolConstants.DEFAULT_HEADER_SIZE - 4;
		short calculateCheckSum = CheckSumUtil.calculate(in.nioBuffer(),0,checksumContentLength);
		if (calculateCheckSum != checksum) {
			if (logger.isWarnEnabled()) {
				logger.warn("checksum not validate client {},server {},checksum content length {}.skip current cmd message.",checksum, calculateCheckSum,checksumContentLength);
			}
			// 跳过当前指令数据内容
			in.skipBytes(checksumContentLength);
			return null;
		}
		
		// 指令号
		short messageId = in.readShort();
		int status = in.readInt();
		IMessage msg = MessageManager.me().create();
		if (in.isReadable()) {
			// 验证校验和是否有效
			byte[] body = new byte[bodyLength];
			in.readBytes(body);
			msg.setBody(body);
		}
		msg.setStatus(status);
		msg.setLength(bodyLength);
		msg.setCommandId(messageId);
		return msg;
	}

}
